<?php
/**
 * Created by PhpStorm.
 * User: hongls
 * Date: 2016/3/24
 * Time: 9:45
 * 卡券管理
 */
namespace Shop\Controller;
use Common\Model\CouponModel;
use Shop\BaseController;
use Think\Page;

class CardController extends BaseController
{
    /**
     * index 卡券列表
     */
    public function index(){
        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        //分页
        $count = $card_info->count();
        $Page = new Page($count, 10);
        fetchPage($this->smarty, $Page);
        //分页
        $list = $card_info
            ->field('id,title,stock,status,authorName,type,launchNum,onlineNum')
            ->limit($Page->firstRow.','.$Page->listRows)
            ->select();
        //领取人数

        //投放数量
        $this->smarty->assign('list',$list);
        $this->smarty->display('Card/index.html');
    }
    /**
     * log 使用记录
     */
    public function log(){
        $this->smarty->display('Card/log.html');
    }
    /**
     * add添加卡券页面
     */
    public function add(){
        $restaurant = M('s_restaurant',null,DB_MAIN_CFG);
        $restaurant_list = $restaurant->field('id,restaurantName')->where('status='.ENABLE_ENABLE)->select();
        $cardType = CouponModel::getCardType();
        $this->smarty->assign('restaurant_list',$restaurant_list);
        $this->smarty->assign('card_type',$cardType);
        $this->smarty->display('Card/add.html');
    }
    /**
     * cardUpdate 更改卡券状态
     */
    public function cardUpdate(){
        $id = I('get.id', null, 'intval');
        $card_info = M('card_base_info',null,DB_MAIN_CFG);
        $item = $card_info->find($id);
        if(empty($item)){
            $this->error('没有存在该卡券');
        }
        if($item['status']) {
            $result = $card_info->where('id=' . $id)->setField('status', ENABLE_DISABLE);
        }else{
            $result = $card_info->where('id=' . $id)->setField('status', ENABLE_ENABLE);
        }
        if ($result) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }
    /**
     * edit 编辑卡券
     */
    public function edit(){

    }

    /**
     * record 根据单个卡券查看该卡券使用记录
     */
    public function record(){

    }
    /**
     * ajaxAddCard ajax创建卡券信息表（除电子卡券）
     */
    public function ajaxAddCard(){
        $uid = session('auth_id');
        $username = session('username');
        $cardInfo = M('card_base_info',null,DB_MAIN_CFG);
        //验证数组
        //第几次ajax
        $p = I('post.p',null,'intval');
        $rules = array(
            array('title','require','标题必须要填写'),
            array('stock','require','库存必须要填写'),
            array('restaurantId','require','商户必须要选择'),
            array('color','require','颜色必须要选择'),
            array('type','require','卡券类型必须要选择'),
        );
        //自动完成数组
        $auto = array(
            array('updateTime', 'time', 3, 'function'),
            array('authorId',$uid),
            array('authorName',$username)
        );
        if($data = $cardInfo->validate($rules)->auto($auto)->create()){
            $storeId = I('post.storeId',null);
            $availableDay = I('post.availableDay',null);
            //判断是否选择门店
            if(empty($storeId)){
                $ajaxData = array(
                  'status' => AJAX_FASLE,
                  'msg' => '门店必须要选择',
                );
                $this->ajaxReturn($ajaxData);
            }
            //判断是否选择时间段
            if(empty($availableDay)){
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '可用时间段必须要选择',
                );
                $this->ajaxReturn($ajaxData);
            }
            //把门店和时间段 转成 **,**存入数据库
            $data['storeId'] = implode(',',$storeId);
            $data['availableDay'] = implode(',',$availableDay);
            //添加卡券基础信息表里面
            $result = $cardInfo->add($data);
            //根据库存生成相对应的卡券号
            if($result){
                $cardlist_data = array(
                    'cardTitle' => $data['title'],
                    'restaurantId' => $data['restaurantId'],
                    'cardId'   => $result,
                    'createTimestamp' => time(),
                );
                $ajaxData =array(
                    'status' => AJAX_SUCCESS,
                    'data' => $cardlist_data,
                    'msg' => '添加成功',
                );
                $this->ajaxReturn($ajaxData);
            }else{
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '添加失败',
                );
                $this->ajaxReturn($ajaxData);
            }
        }else{
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => $cardInfo->getError(),
            );
            $this->ajaxReturn($ajaxData);
        }
    }


    /**
     * ajaxElectCard ajax 创建电子卡券
     */
    public function ajaxElectCard(){
        $uid = session('auth_id');
        $username = session('username');
        $cardInfo = M('card_base_info',null,DB_MAIN_CFG);
        $path = I('post.path',null);
        //验证数组
        $rules = array(
            array('title','require','标题必须要填写'),
            array('restaurantId','require','商户必须要选择'),
            array('color','require','颜色必须要选择'),
            array('type','require','卡券类型必须要选择'),
        );
        //自动完成数组
        $auto = array(
            array('updateTime', 'time', 3, 'function'),
            array('authorId',$uid),
            array('authorName',$username)
        );
        if($data = $cardInfo->validate($rules)->auto($auto)->create()){
            $storeId = I('post.storeId',null);
            $availableDay = I('post.availableDay',null);
            //判断是否选择门店
            if(empty($storeId)){
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '门店必须要选择',
                );
                $this->ajaxReturn($ajaxData);
            }
            //判断是否选择时间段
            if(empty($availableDay)){
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '可用时间段必须要选择',
                );
                $this->ajaxReturn($ajaxData);
            }
            //把门店和时间段 转成 **,**存入数据库
            $data['storeId'] = implode(',',$storeId);
            $data['availableDay'] = implode(',',$availableDay);
            //添加卡券基础信息表里面
            $result = $cardInfo->add($data);
            //根据库存生成相对应的卡券号
            if($result){
                $this->implodeExcel($result,$path);
                $ajaxData =array(
                    'status' => AJAX_SUCCESS,
                    'msg' => '添加成功',
                    'msg' => '添加成功',
                );
                $this->ajaxReturn($ajaxData);
            }else{
                $ajaxData = array(
                    'status' => AJAX_FASLE,
                    'msg' => '添加失败',
                );
                $this->ajaxReturn($ajaxData);
            }
        }else{
            $ajaxData = array(
                'status' => AJAX_FASLE,
                'msg' => $cardInfo->getError(),
            );
            $this->ajaxReturn($ajaxData);
        }
    }

    /**
     * 导入电子卡券的excel表
     * @param $cardId  卡券id
     * @param $path excel路径
     */
    function implodeExcel($cardId,$path){
        //导入excel
        vendor("PHPExcel.PHPExcel");
        $path = '.' . $path;
        //设置excel的类型
        $objReader = \PHPExcel_IOFactory::createReader('Excel2007');
        //打开excel的文件
        $objPHPExcel = $objReader->load($path,$encode='utf-8');
        //只获取第一页sheet
        $sheet = $objPHPExcel->getSheet(0);
        //计算行数
        $highestRow = $sheet->getHighestRow(); // 取得总行数
        $nowTime = time();
        for($i=2;$i<=$highestRow;$i++)
        {
            $datalist[] = array(
                //第一列只获取卡券号
                'code' => $objPHPExcel->getActiveSheet()->getCell("A".$i)->getValue(),
                //第二列获取密码
                'password' => $objPHPExcel->getActiveSheet()->getCell("B".$i)->getValue(),
                'creatTime' => $nowTime,
                'cardId' => $cardId,
            );
        }
        //计算个数
        $stock = count($datalist);
        //添加到电子卡券表
        $result = M('elect_cart_list',null,DB_MAIN_CFG)->addAll($datalist);
        if($result){
            //删除excel文件
            @unlink($path);
            //更新卡券表中的库存
            M('card_base_info',null,DB_MAIN_CFG)->where('id=' . $cardId)->setField('stock',$stock);
        }
    }
}
